package com.liugui;

/**
 * 模拟死锁
 *
 * @ClassName: DeadLockDemo
 * @Author: liugui
 * @Date: 2021-05-20 17:47
 **/
public class DeadLockDemo implements Runnable {

    private static Alis    alis  = new Alis();       // 实例化static型对象
    private static Alien   alien = new Alien();       // 实例化static型对象
    private boolean flag  = false;  // 声明标志位，判断那个先说话

    @Override
    public void run() {
        if (flag){
            synchronized (alis){
                alis.say();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (alien){
                    alis.get();
                }
            }
        }else {
            synchronized (alien){
                alien.say();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (alis){
                    alien.get();
                }
            }
        }
    }

    public static void main(String[] args) {
        DeadLockDemo d1 = new DeadLockDemo();
        DeadLockDemo d2 = new DeadLockDemo();
        d1.flag = true;
        d2.flag = false;
        Thread t1 = new Thread(d1);
        Thread t2 = new Thread(d2);

        t1.start();
        t2.start();
    }
}


class Alis {
    public void say() {
        System.out.println("Alis对Alien说：“你给我画，我就把书给你。”");
    }

    public void get() {
        System.out.println("Alis得到画了。");
    }
}

class Alien {
    public void say() {
        System.out.println("Alien对Alis说：“你给我画，我就把书给你。”");
    }

    public void get() {
        System.out.println("Alien得到画了。");
    }

}

